package view.GUI.adminView.coreData.people.staff;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import model.data.tableModel.person.Person;
import model.data.tableModel.person.Staff;

import org.controlsfx.dialog.Dialogs;
import org.controlsfx.validation.ValidationSupport;

import enums.GUIText;
import enums.Message;
import enums.Status;
import view.GUI.mainView.MainView;
import view.Validator.PasswordValidator;

public final class NewStaff extends StaffView {

	protected ComboBox<Person> cmbPerson;
	private Label lblPerson;

	public NewStaff(MainView instance) {
		super(false, GUIText.NEWSTAFF, instance);

		// bug in ControlsFX see https://bitbucket.org/controlsfx/controlsfx/issue/285/validator-support-change-resize-behavior
		valSup.registerValidator(txtPW, true, new PasswordValidator());
		valSup.registerValidator(txtValidatePW, true, new PasswordValidator());
		lblPerson = new Label(GUIText.PERSON.toString());
		cmbPerson = new ComboBox<>();
		cmbPerson.getItems().addAll(super.owner.getPersons());

		cmbPerson.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Person>() {

			@Override
			public void changed(ObservableValue<? extends Person> arg0, Person arg1, Person newValue) {
				lblShowNick.setText(Staff.createNickname(newValue.getFirstName(), newValue.getLastName(), newValue.getRoom()));
			}
		});

		super.addNode(lblPerson, 0, 0);
		super.addNode(cmbPerson, 1, 0);
		
		ValidationSupport.setRequired(cmbPerson, true);
		try {
			start(new Stage());
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
	}

	@Override
	protected boolean save() {
		if (txtPW.getText() != null || txtValidatePW.getText() != null) {
			if (txtPW.getText().equals(txtValidatePW.getText())) {
				Person p = cmbPerson.getSelectionModel().getSelectedItem();
				
				boolean isAlreadyStaff = false;
				for(Staff s: owner.getStaff()){
					if(s.getPerson().equals(p)){
						isAlreadyStaff = true;
					}
				}
				if(isAlreadyStaff){
					Dialogs.create()
							.message(Message.ISALREADYSTAFF.toString())
							.showError();
					return false;
				}
				
				Staff s = Staff
						.createNewStaff(p, null, null, Status.ACTIVE);
				owner.setNewPassword(s, txtPW.getText());
				s.writeToDB();
				owner.addStaff(s);
				return true;
			} else {
				Dialogs.create().message(Message.PWVERIFICATIONWRONG.toString()).showError();
				return false;
			}
		} else {
			Dialogs.create().message(Message.MSGMISSINGINFO.toString()).showError();
			return false;
		}
	}
}
